package com.mc.union;

public class QuickUnion {
	
	private int[] id;
	
	public QuickUnion(int n){
		id = new int[n];
		for(int i=0;i<n;i++){
			id[i]=i;
		}
	}
	
	public void union(int p,int q){
		if(connected(p,q))return;
		int index = find(p);
		id[index]=find(q);
	}
	
	public int find(int p){
		while(id[p]!=p){
			p = id[p];
		}
		return p;
	}
	public boolean connected(int p,int q){
		return find(q)==find(p);
	}
}
